<template>
    <el-dialog :model-value="show" title="新建项目" width="80%" align-center
               :close-on-click-modal="false" :before-close="shut"
               destroy-on-close append-to-body>
        <el-form ref="projectRef" :model="project" :rules="rules"
                 label-width="170px" status-icon label-position="left"
        >
            <el-form-item label="项目logo">
                <Logo ref="LogoRef" v-model:logoFile="logoFile"/>
                <div style="margin-left: 1em">
                    格式为图像格式，不超过2M，文件数量限一个。
                </div>
            </el-form-item>
            <el-divider><span style="display: flex;align-items: center"><el-icon><StarFilled/></el-icon>基本信息<el-icon><StarFilled/></el-icon></span>
            </el-divider>
            <el-form-item label="项目名称" prop="name">
                <el-input v-model="project.name" clearable/>
            </el-form-item>
            <el-form-item label="项目类型" prop="types">
                <el-select v-model="project.types" placeholder="请选择">
                    <el-option value="创新训练项目"/>
                    <el-option value="创业训练项目"/>
                    <el-option value="创业实践项目"/>
                </el-select>
            </el-form-item>
            <el-form-item label="所属批次" prop="batch">
                <el-autocomplete clearable placeholder="请输入所属批次"
                                 v-model="project.batch" :fetch-suggestions="querySearch"
                />
            </el-form-item>
            <el-form-item label="所属领域" prop="tags">
                <el-checkbox-group :max="3" size="" v-model="project.tags">
                    <el-checkbox-button v-for="tag in tags" :key="tag" :label="tag"/>
                </el-checkbox-group>
            </el-form-item>
            <el-form-item label="项目简介" prop="profiles">
                <el-input type="textarea" :rows="4" :minlength="100" :maxlength="1000" show-word-limit
                          placeholder="可拆分为产品描述、用户群体、项目愿景、竞争对手等方面详细描述，不少于100字，但不超过1000字"
                          v-model="project.profiles"/>
            </el-form-item>
            <el-form-item label="学校科技成果转化" prop="achievementIsTransform">
                <template #label>
                    <span>
                        学校科技成果转化
                        <el-tooltip trigger="click" placement="top"
                                    content="学校科技成果转化项目是指创业团队所使用核心科技成果的所有权是学校的项目">
                            <el-button link><el-icon><InfoFilled/></el-icon></el-button>
                        </el-tooltip>
                    </span>
                </template>
                <el-radio-group v-model="project.achievementIsTransform">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="参赛申报人为科技成果的第一完成人或所有人" prop="declarerIsAchievementOwner">
                <el-radio-group v-model="project.declarerIsAchievementOwner">
                    <el-radio :label="1">是</el-radio>
                    <el-radio :label="0">否</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="项目成熟度" min-width="150" prop="maturity">
                <template #default="scope">
                    <el-tag v-if="!project.types" disabled>请先选择项目类型</el-tag>
                    <div v-else>
                        <el-tag>{{ project.maturity }}</el-tag>
                        <el-button size="small" type="primary" style="margin-left: 1rem"
                                   @click="maturityDialog.visible = true">请选择</el-button>
                    </div>
                </template>
            </el-form-item>
            <el-form-item prop="grade" label="立项等级">
                <el-select v-model="project.grade" placeholder="请选择">
                    <el-option :value="0" label="校级"/>
                    <el-option :value="1" label="省级"/>
                    <el-option :value="2" label="国家级"/>
                </el-select>
            </el-form-item>
            <el-form-item prop="projectEntryStatus" label="项目进度">
                <el-select v-model="project.projectEntryStatus" placeholder="请选择">
                    <el-option v-for="(status,index) in entryStatus" :value="index"  :label="status"/>
                </el-select>
            </el-form-item>
            <el-form-item prop="remark" label="项目备注">
                <el-input clearable placeholder="项目备注" v-model="project.remark" type="textarea" :rows="4"/>
            </el-form-item>
            <el-divider><span style="display: flex;align-items: center"><el-icon><StarFilled/></el-icon>团队成员<el-icon><StarFilled/></el-icon></span>
            </el-divider>
            <el-form-item prop="studentNumber">
                <template #label>
                    <span>
                        参与学生数
                        <el-tooltip trigger="hover" placement="top"
                                    content="参与学生数不包括负责人自己(创建项目者)，且确定后将无法修改!">
                            <el-button link><el-icon><InfoFilled/></el-icon></el-button>
                        </el-tooltip>
                    </span>
                </template>
                <el-input-number :min="0" v-model="project.studentNumber"/>
            </el-form-item>
            <el-form-item label="参与学生">
                <InviteStudent :studentNumber="project.studentNumber" v-model:studentList="studentList"/>
            </el-form-item>
            <el-form-item prop="hostInstructor">
                <template #label>
                    <span>
                        第一指导教师
                        <el-tooltip trigger="hover" placement="top"
                                    content="一旦项目创建成功后，第一指导老师将无法更改!">
                    <el-button link><el-icon><InfoFilled/></el-icon></el-button>
                </el-tooltip>
                    </span>
                </template>
                <InviteHostInstructor v-model="project.hostInstructor"/>
            </el-form-item>
            <el-form-item label="第二指导教师" prop="instructors">
                <InviteInstructor v-model:instructorList="instructorList"/>
            </el-form-item>
            <el-divider><span style="display: flex;align-items: center"><el-icon><StarFilled/></el-icon>所属文件<el-icon><StarFilled/></el-icon></span>
            </el-divider>
            <el-form-item label="项目文件">
                <Resource v-model:resourceFileList="resourceFileList"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="submitForm(projectRef)">完成</el-button>
                <el-button @click="resetForm">重置</el-button>
                <el-button type="danger" @click="$emit('update:show',false)">取消</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="maturityDialog.visible" :append-to-body='true' :title="maturityDialog.title" width="80%"
               @close="maturityDialog.visible = false">
        <el-table highlight-current-row table-layout="fixed"
                  :data="maturities" @current-change="rowClick">
            <el-table-column align="center" width="55">
                <template #default="scope">
                    <el-radio :model-value="project.maturity" :label="scope.row.value">{{}}</el-radio>
                </template>
            </el-table-column>
            <el-table-column prop="value" label="成熟度" witdh="100" align="center"/>
            <el-table-column prop="standard" label="判断标准" min-width="500" align="center"/>
            <el-table-column prop="need" label="支撑材料" width="500" align="center"/>
        </el-table>
    </el-dialog>
</template>

<script setup>
import {computed, reactive, ref} from 'vue'

//api
import {createProjectApi, createProjectResourceFileApi, updateProjectLogoFileApi} from "@/apis/project";
import {InfoFilled, StarFilled} from "@element-plus/icons-vue";

import Logo from "@/views/User/MyProject/CreateProject/components/Logo.vue";
import Resource from "@/views/User/MyProject/CreateProject/components/Resource.vue";
import {createProjectInstructorApi, updateProjectHostInstructorApi,} from "@/apis/instructorInvolveProject";
import {createProjectStudentApi,} from "@/apis/studentInvolveProject";

import InviteStudent from "@/views/User/MyProject/CreateProject/components/InviteStudent.vue";
import InviteHostInstructor from "@/views/User/MyProject/CreateProject/components/InviteHostInstructor.vue";
import InviteInstructor from "@/views/User/MyProject/CreateProject/components/InviteInstructor.vue";
import {getLogoUploadPresigned, getProjectUploadPresigned, uploadByPresignedUrl} from "@/apis/file";
import {
    getMaturityEntrepreneurship,
    getMaturityInnovation,
    getProjectBatches,
    getProjectEntryStatus,
    getProjectTags
} from "@/apis/enum";

const props = defineProps(["show"])
const emits = defineEmits(["update:show", "reload"])

//TODO 暂时同步获取,异步没有接口
const batches = ref(getProjectBatches())
// getBatchesApi().then((
//     res => batches.value = res
// ))

//暂时同步获取,缺少接口
const tags = ref(getProjectTags())
// getSearchTagsApi().then((
//     res => tags.value = res.data
// ))
//项目进度
const entryStatus = getProjectEntryStatus()

const LogoRef = ref(null)
const logoFile = ref("")
const studentList = ref([])
const instructorList = ref([]);
const resourceFileList = ref([])

//新建项目
const projectRef = ref()
//项目信息
const project = ref({
    name: "",
    types: "",
    batch: "",
    tags: [],
    grade:"",
    profiles: "",
    achievementIsTransform: 1,
    declarerIsAchievementOwner: 1,
    hostInstructor:"",
    maturity: "0.0",
    studentNumber: 5,
    resourceId: [],
    status:0,
    projectEntryStatus:0,
    remark:""
})
const maturityDialog = reactive({
    visible: false,
    title: "选择成熟度"
})
const maturities = computed(() => {
    if (!project.value.types) return []
    return project.value.types === "创新训练项目" ? getMaturityInnovation() : getMaturityEntrepreneurship()
})
const rowClick = row => {
    project.value.maturity = row.value
    maturityDialog.visible = false
}
const rules = {
    name: [{required: true, message: '项目名称不能为空!', trigger: ['blur','change']}],
    types: [{required: true, message: '项目类型不能为空!', trigger: ['blur','change'],}],
    batch: [{required: true, message: '项目批次不能为空!', trigger: ['blur','change'],}],
    tags: [{required: true, message: '项目所属领域不能为空!', trigger: ['blur','change']}],
    grade: [{required: true, message: '项目立项等级不能为空!', trigger: ['blur','change']}],
    profiles: [
        {required: true, message: '项目简介不能为空', trigger: ['blur','change']},
        {required: true, min: 100, message: '至少100字', trigger: ['blur','change']},
    ],
    achievementIsTransform: [{required: true, message: '学科科技成果转化不能为空', trigger: ['blur','change'],}],
    declarerIsAchievementOwner: [{required: true, message: '参赛申报人为科技成果的第一完成人或所有人不能为空', trigger: ['blur','change'],}],
    maturity: [{required: true, message: '项目成熟度不能为空', trigger: ['blur','change'],}],
    studentNumber: [{required: true, message: '参与学生数不能为空', trigger: ['blur','change'],}],
    hostInstructor: [{required: true, message:'第一指导教师不能为空',trigger:['blur','change'],}],
    projectEntryStatus: [{required: true, message: '项目进度不能为空', trigger: ['blur','change'],}]
}
/**
 * 重置表单
 */
const resetForm = () => {
    projectRef.value.resetFields()
    logoFile.value = ""
    LogoRef.value.resetLogo()
    studentList.value = []
    instructorList.value = []
    resourceFileList.value = []
}
const submitForm = formEl => {
    if (!formEl) return
    formEl.validate(async valid => {
        if (valid) {

            let res = await createProjectApi(project.value)
            if (logoFile.value) {
                const url = await getLogoUploadPresigned(logoFile.value.name);
                await uploadByPresignedUrl(url.data, logoFile.value)
                await updateProjectLogoFileApi(res.data, url.data.slice(0, url.data.lastIndexOf('?')))
            }
            if (studentList.value.length) {
                for (const student of studentList.value) {
                    await createProjectStudentApi(res.data, student.id)
                }
            }
            if (instructorList.value.length) {
                for (const instructor of instructorList.value) {
                    await createProjectInstructorApi(res.data, instructor.id)
                }
            }
            if (resourceFileList.value.length) {
                for (const file of resourceFileList.value) {
                    file.status = "uploading"
                    const url = await getProjectUploadPresigned(file.name);
                    file.timer = setInterval(() => {
                        file.percentage++
                        if (file.percentage === 99) clearInterval(file.timer)
                    }, 10)
                    await uploadByPresignedUrl(url.data, file)
                    await createProjectResourceFileApi(res.data, url.data.slice(0, url.data.lastIndexOf('?')))
                    clearInterval(file.timer)
                    file.percentage = 100
                    file.status = "success"
                }
            }
            ElMessage.success('项目创建成功')
            resetForm()
            emits("update:show", false)
            emits("reload")
        }
    })
}


const shut = () => {
    ElMessageBox.confirm(
        '确定关闭吗?',
        'Warning',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        resetForm()
        emits("update:show", false)
    }).catch()
}

const querySearch = async (queryString, cb) => {
    const results = queryString
        ? batches.value.filter(createFilter(queryString))
        : batches.value
    cb(results)
}
const createFilter = (queryString) => {
    return (batch) => {
        return (
            batch.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
</script>

<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}

.el-form-item {
    margin-bottom: 20px;
}

:deep(.el-form-item__label) {
    line-height: normal;
}

:deep(.el-checkbox-button .el-checkbox-button__inner) {
    border: 1px solid #DCDFE6;
    margin: 0 1em 1em 0;
    border-radius: 4px;
}

:deep(.el-checkbox-button.is-checked .el-checkbox-button__inner) {
    border: 1px solid #409EFF;
}
</style>